package repository

import (
	"RocFamilySystem/models"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type SysRoleRepository struct {
	Db *gorm.DB
}

func init() {
	registerContainer["SysRoleRepository"] = &SysRoleRepository{}
}

func (r *SysRoleRepository) SetDB(db *gorm.DB) {
	r.Db = db
}

// InsertSysRole 添加系统系统角色
func (r *SysRoleRepository) InsertSysRole(sysRole *models.SysRole) {

	//开启事务
	db := r.Db.Begin()
	defer handleTransactional(db)
	now := models.LocalTime(time.Now())
	sysRole.CreateTime = &now
	err := db.Save(sysRole).Error
	handleRepositoryErr(err, "添加系统角色失败")
}

// DeleteSysRole 删除系统系统角色
func (r *SysRoleRepository) DeleteSysRole(sysRoleId int) {
	db := r.Db.Begin()
	defer handleTransactional(db)

	err := db.Delete(&models.SysRole{Id: &sysRoleId}).Error
	handleRepositoryErr(err, "添加系统角色失败")
}

// DeleteSysRoleBatch 批量删除系统角色
func (r *SysRoleRepository) DeleteSysRoleBatch(ids []string) {
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Where("id in (?)", ids).Delete(models.SysRole{}).Error
	handleRepositoryErr(err, "删除系统缓存失败！")
}

// UpdateSysRole 修改系统系统角色
func (r *SysRoleRepository) UpdateSysRole(sysRole *models.SysRole) {
	now := models.LocalTime(time.Now())
	sysRole.UpdateTime = &now

	db := r.Db.Begin()
	defer handleTransactional(db)

	err := db.Model(sysRole).Omit("id", "create_time").Updates(sysRole).Error
	handleRepositoryErr(err, "修改系统角色失败")
	err = db.Exec("delete from sys_role_menus where sys_role_id = ?", *sysRole.Id).Error
	handleRepositoryErr(err, "修改系统角色失败")
	db.Model(sysRole).Association("SysMenus").Append(sysRole.SysMenus)
	err = db.Exec("delete from rocfamily.sys_role_permissions where sys_role_id = ?", *sysRole.Id).Error
	handleRepositoryErr(err, "修改系统角色失败")
	err = db.Model(sysRole).Association("SysPermissions").Append(sysRole.SysPermissions)
	handleRepositoryErr(err, "修改系统角色失败")
}

// SelectSysRole 查询系统系统角色
func (r *SysRoleRepository) SelectSysRole(sysRole *models.SysRole, pageNum, pageSize int) ([]models.SysRole, int) {
	var (
		list  []models.SysRole
		total int64
	)
	db := r.Db.Model(&models.SysRole{})

	if sysRole != nil {
		if sysRole.RoleName != nil {
			db = db.Where("role_name like ?", fmt.Sprintf("%%%s%%", *sysRole.RoleName))
		}
	}
	//获取总数
	db.Count(&total)

	//获取列表
	db.Offset(pageSize * pageNum).Limit(pageSize)
	db.Find(&list)

	return list, int(total)
}

// SelectSysRoleById 查询系统角色通过ID
func (r *SysRoleRepository) SelectSysRoleById(id int) models.SysRole {
	var sysRole models.SysRole
	err := r.Db.Preload("SysMenus", func(db *gorm.DB) *gorm.DB {
		return db.Order("weight asc")
	}).Preload("SysPermissions").First(&sysRole, "id = ?", id).Error
	if err != nil {
		handleRepositoryErr(err, "查询失败")
	}
	return sysRole
}
